package model

import (
	"errors"
	"manager/db"

	"github.com/lerryxiao/gorm"
)

func createTable(db *gorm.DB, tab interface{}, cb func(interface{})) error {
	if db.HasTable(tab) == false {
		if err := db.Set("gorm:table_options", "").CreateTable(tab).Error; err != nil {
			return err
		}
		if cb != nil {
			cb(tab)
		}
	}
	return nil
}

// CheckTable 检查表
func CheckTable(conn *gorm.DB) error {
	if conn == nil {
		conn = db.GetDB()
	}
	if conn == nil {
		return errors.New("no db connection opend")
	}

	if err := createTable(conn, &Lamp{}, nil); err != nil {
		return err
	}

	if err := createTable(conn, &Board{}, nil); err != nil {
		return err
	}

	return nil
}
